package com.rm.zeyou.util.sms;

import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 短信宝
 */
@Slf4j
@Component
public class SmsSample {

    @Value("${sms.username}")
    private String username; // 在短信宝注册的用户名
    @Value("${sms.password}")
    private String password; // 在短信宝注册的密码

    public String sendSms(String phone, String randomCode, String type) {

        if (CheckEmptyUtil.isEmpty(phone)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.PHONE_NUMBER_NULL);
        }
        // if (! ValitedPhone.isValidPhoneNumber(phone)) {
        //     throw new ErrorCodeException(ErrorCodeExceptionEnum.PHONE_NUMBER_ERROR);
        // }
        // String testPhone = "15929943563";
        String content;
//        if (CommonConstants.SMS_USER_REGISTER.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于注册或者登录,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else if (CommonConstants.SMS_USER_FORGET_PASSWORD.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于修改密码,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else if (CommonConstants.MERCHANTS_SETTLE.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于申请门店入驻,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else if (CommonConstants.RECRUITMENT.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于申请技师,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else if (CommonConstants.CITY_PARTNERS.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于申请城市合伙人,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else if (CommonConstants.CHANGE_TEL.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于更换绑定手机号,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else if (CommonConstants.BLIND_TEL.equals(type)) {
//            content = String.format("【忆佳人】您的验证码是%s，此验证码只用于绑定手机号,60秒内有效。若非本人操作请忽略此消息。", randomCode);
//        } else {
//            throw new ErrorCodeException(ErrorCodeExceptionEnum.SEND_TYPE_ERROR);
//        }
         content=String.format("【忆佳人】您的验证码是%s，此验证码只用于注册或者登录,60秒内有效。若非本人操作请忽略此消息。", randomCode);
        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(username).append("&");
        httpArg.append("p=").append(md5(password)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(encodeUrlString(content, "UTF-8"));

        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);
        return result;
    }

    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }
}